package org.squirrel.squirrel_ai_agent_backend.controller.demo.invoke;

/**
 * Http方式调用AI
 */
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;

public class HttpAiInvoke {
    public static void main(String[] args) {
        // 从环境变量获取API密钥，也可以直接在这里设置为字符串
        String apiKey = TestApiKey.test_api_key;
        if (apiKey == null || apiKey.isEmpty()) {
            System.err.println("请设置环境变量DASHSCOPE_API_KEY");
            return;
        }

        // API端点URL
        String url = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";

        // 构建请求体JSON
        JSONObject requestBody = new JSONObject();
        requestBody.put("model", "qwen-plus");

        // 构建消息数组
        JSONArray messages = new JSONArray();

        // 系统消息
        JSONObject systemMsg = new JSONObject();
        systemMsg.put("role", "system");
        systemMsg.put("content", "You are a helpful assistant.");
        messages.add(systemMsg);

        // 用户消息
        JSONObject userMsg = new JSONObject();
        userMsg.put("role", "user");
        userMsg.put("content", "你是谁？");
        messages.add(userMsg);

        requestBody.put("messages", messages);

        // 发送POST请求
        try (HttpResponse response = HttpRequest.post(url)
                .header("Authorization", "Bearer " + apiKey)
                .header("Content-Type", "application/json")
                .body(requestBody.toString())
                .execute()) {

            // 输出响应结果
            System.out.println("响应状态码: " + response.getStatus());
            System.out.println("响应内容: " + response.body());

        } catch (Exception e) {
            System.err.println("请求发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
